package cn.kdyzm.twofa.controller.api;

import cn.kdyzm.twofa.entity.SysUser;
import cn.kdyzm.twofa.models.WrapperResult;
import cn.kdyzm.twofa.models.dto.LoginReq;
import cn.kdyzm.twofa.models.vo.LoginResultVo;
import cn.kdyzm.twofa.service.ILoginService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author kdyzm
 * @date 2025/6/16
 */
@RestController
@RequestMapping("/login")
@Slf4j
@AllArgsConstructor
public class LoginApi {

    private final ILoginService loginService;

    @PostMapping
    public WrapperResult<LoginResultVo> login(LoginReq req, HttpServletResponse response) {
        SysUser sysUser = loginService.login(req.getUserName(), req.getPassword());
        if (Objects.isNull(sysUser)) {
            return WrapperResult.faild("用户名或密码错误");
        }
        // Create and set cookie
        Cookie userIdCookie = new Cookie("userId", sysUser.getId() + "");
        userIdCookie.setPath("/");
        userIdCookie.setMaxAge(7 * 24 * 60 * 60);
        userIdCookie.setHttpOnly(true);
        response.addCookie(userIdCookie);
        LoginResultVo vo = new LoginResultVo();
        vo.setTowFaEnabled(sysUser.getTowFaEnabled());
        return WrapperResult.success(vo);
    }
}
